﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace OpenId2Ids.EntityFrameworkCore;

/* This class is needed for EF Core console commands
 * (like Add-Migration and Update-Database commands) */
public class OpenId2IdsDbContextFactory : IDesignTimeDbContextFactory<OpenId2IdsDbContext>
{
    public OpenId2IdsDbContext CreateDbContext(string[] args)
    {
        OpenId2IdsEfCoreEntityExtensionMappings.Configure();

        var configuration = BuildConfiguration();
        var connectionString = configuration.GetConnectionString("Openid2Ids");

        Console.WriteLine($"ConnectionString: {connectionString}");

        var builder = new DbContextOptionsBuilder<OpenId2IdsDbContext>()
            .UseMySql(connectionString, ServerVersion.Parse("8.1"));
        var context = new OpenId2IdsDbContext(builder.Options);

        return context;
    }

    private static IConfigurationRoot BuildConfiguration()
    {
        var basePath = Path.Combine(Directory.GetCurrentDirectory(), "../OpenId2Ids.DbMigrator/");
        Console.WriteLine($"Base Path: {Path.GetFullPath(basePath)}");

#if DEBUG
        var builder = new ConfigurationBuilder()
            .SetBasePath(basePath)
            .AddJsonFile("appsettings.Development.json", optional: false);
#else
            var builder = new ConfigurationBuilder()
                .SetBasePath(basePath)
                .AddJsonFile("appsettings.json", optional: false);
#endif

        return builder.Build();
    }
}
